<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="190px">
    <el-form-item label="项目编号" prop="projectNum">
            <el-select  :disabled="isEditMode"
                v-model="dataForm.projectNum"
                placeholder="请选择项目编号"
                class="label_len"
                >
              <el-option
                  v-for="item in projectList"
                  :key="item.prProjectNumber"
                  :label="item.prProjectNumber + ' ' + item.prProjectName"
                  :value="item.prProjectNumber">
              </el-option>
            </el-select>
          </el-form-item>
    <el-form-item label="调查户数" prop="houseSize">
      <el-input type="number" v-model="dataForm.houseSize" placeholder="调查户数" @change="updateEvaluationFields"></el-input>
    </el-form-item>
     <el-table :data="evaluationItems" style="width: 100%">
      <el-table-column prop="label" label="评分项" width="180"></el-table-column>
      <el-table-column label="优">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.excellentCount"
            type="number"
            min="0"
            placeholder="输入户数" @input="recalculateAll()" 
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="良">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.goodCount"
            type="number"
            min="0"
            placeholder="输入户数" @input="recalculateAll()" 
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="中">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.averageCount"
            type="number"
            min="0"
            placeholder="输入户数" @input="recalculateAll()" 
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="较差">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.belowAverageCount"
            type="number"
            min="0"
            placeholder="输入户数" @input="recalculateAll()"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="差">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.poorCount"
            type="number"
            min="0"
            placeholder="输入户数" @input="recalculateAll()"
          ></el-input>
        </template>
      </el-table-column>
    </el-table>
    <el-form-item label="故障情况" prop="faultState">
      <el-input v-model="dataForm.faultState" placeholder="故障情况"></el-input>
    </el-form-item>
    
    <el-form-item label="用户满意度" prop="userState">
      <el-input v-model="dataForm.userState" placeholder="用户满意度" readonly></el-input>
    </el-form-item>
    <el-form-item label="土壤质地C11" prop="c11">
      <el-input type="number" v-model="dataForm.c11" placeholder="土壤质地C11" readonly></el-input>
    </el-form-item>
    <el-form-item label="耕前植被情况C12" prop="c12">
      <el-input type="number" v-model="dataForm.c12" placeholder="耕前植被情况C12" readonly></el-input>
    </el-form-item>
    <el-form-item label="种植方式C13" prop="c13">
      <el-input type="number" v-model="dataForm.c13" placeholder="种植方式C13" readonly></el-input>
    </el-form-item>
    <el-form-item label="土壤特性C14" prop="c14">
      <el-input type="number" v-model="dataForm.c14" placeholder="土壤特性C14" readonly></el-input>
    </el-form-item>
    <el-form-item label="耕后地表平整情况C21" prop="c21">
      <el-input type="number" v-model="dataForm.c21" placeholder="耕后地表平整情况C21" readonly></el-input>
    </el-form-item>
    <el-form-item label="碎土情况C22" prop="c22">
      <el-input type="number" v-model="dataForm.c22" placeholder="碎土情况C22" readonly></el-input>
    </el-form-item>
    <el-form-item label="耕深满足农艺要求情况C23" prop="c23">
      <el-input type="number" v-model="dataForm.c23" placeholder="耕深满足农艺要求情况C23" readonly></el-input>
    </el-form-item>
    <el-form-item label="植被覆盖情况C24" prop="c24">
      <el-input type="number" v-model="dataForm.c24" placeholder="植被覆盖情况C24" readonly></el-input>
    </el-form-item>
    <el-form-item label="驱动轮滑转情况C31" prop="c31">
      <el-input type="number" v-model="dataForm.c31" placeholder="驱动轮滑转情况C31" readonly></el-input>
    </el-form-item>
    <el-form-item label="大小田块适用情况C32" prop="c32">
      <el-input type="number" v-model="dataForm.c32" placeholder="大小田块适用情况C32" readonly></el-input>
    </el-form-item>
    <el-form-item label="地头转弯情况C33" prop="c33">
      <el-input type="number" v-model="dataForm.c33" placeholder="地头转弯情况C33" readonly></el-input>
    </el-form-item>
    <el-form-item label="机耕道及田间行走C34" prop="c34">
      <el-input type="number" v-model="dataForm.c34" placeholder="机耕道及田间行走C34" readonly></el-input>
    </el-form-item>
    <el-row gutter={20}>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="dataForm.remark" placeholder="计算值" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="校验值">
            <el-input v-model="dataForm.remarkValue" placeholder="输入校验值"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          projectNum: '',
          houseSize: '',
          faultState: '',
          userState: '',
          c11: '',
          c12: '',
          c13: '',
          c14: '',
          c21: '',
          c22: '',
          c23: '',
          c24: '',
          c31: '',
          c32: '',
          c33: '',
          c34: '',
          remark: '',
          summaryName: '',
          summaryId: '',
          checkerName: '',
          checkerId: ''
        },
        projectList: [],
        isEditMode: false,
        evaluationResults: {}, // 用于存储每个评估项的选择结果
        evaluationItems: [], // 存储评估项的结构
        dataRule: {
          projectNum: [
            { required: true, message: '项目编号不能为空', trigger: 'blur' }
          ],
          houseSize: [
            { required: true, message: '调查户数不能为空', trigger: 'blur' }
          ],
          faultState: [
            { required: true, message: '故障情况不能为空', trigger: 'blur' }
          ],
          userState: [
            { required: true, message: '用户满意度不能为空', trigger: 'blur' }
          ],
          c11: [
            { required: true, message: '土壤质地C11不能为空', trigger: 'blur' }
          ],
          c12: [
            { required: true, message: '耕前植被情况C12不能为空', trigger: 'blur' }
          ],
          c13: [
            { required: true, message: '种植方式C13不能为空', trigger: 'blur' }
          ],
          c14: [
            { required: true, message: '土壤特性C14不能为空', trigger: 'blur' }
          ],
          c21: [
            { required: true, message: '耕后地表平整情况C21不能为空', trigger: 'blur' }
          ],
          c22: [
            { required: true, message: '碎土情况C22不能为空', trigger: 'blur' }
          ],
          c23: [
            { required: true, message: '耕深满足农艺要求情况C23不能为空', trigger: 'blur' }
          ],
          c24: [
            { required: true, message: '植被覆盖情况C24不能为空', trigger: 'blur' }
          ],
          c31: [
            { required: true, message: '驱动轮滑转情况C31不能为空', trigger: 'blur' }
          ],
          c32: [
            { required: true, message: '大小田块适用情况C32不能为空', trigger: 'blur' }
          ],
          c33: [
            { required: true, message: '地头转弯情况C33不能为空', trigger: 'blur' }
          ],
          c34: [
            { required: true, message: '机耕道及田间行走C34不能为空', trigger: 'blur' }
          ],
          remark: [
            { required: true, message: '备注不能为空', trigger: 'blur' }
          ],
          summaryName: [
            { required: true, message: '汇总人姓名不能为空', trigger: 'blur' }
          ],
          summaryId: [
            { required: true, message: '汇总人id不能为空', trigger: 'blur' }
          ],
          checkerName: [
            { required: true, message: '校核人姓名不能为空', trigger: 'blur' }
          ],
          checkerId: [
            { required: true, message: '校核人id不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    mounted (){
      this.getprojectList(),
      this.updateEvaluationFields(); // 初始化评估项
    },
    methods: {
      validateEvaluationItems() {
        const houseSize = this.dataForm.houseSize;
        let hasError = false;
        let errorMessages = [];

        this.evaluationItems.forEach(item => {
          const excellentCount = parseInt(item.excellentCount) || 0;
          const goodCount = parseInt(item.goodCount) || 0;
          const averageCount = parseInt(item.averageCount) || 0;
          const poorCount = parseInt(item.poorCount) || 0;
          const belowAverageCount=parseInt(item.belowAverageCount) || 0;

          const totalInputCount = excellentCount + goodCount + averageCount + belowAverageCount+poorCount;
          if (totalInputCount > houseSize) {
            hasError = true;
            errorMessages.push(`${item.label}：输入的户数总和不能超过调查户数`);
          } else if (totalInputCount < houseSize) {
            hasError = true;
            errorMessages.push(`${item.label}：优、良、中、差的户数总和必须等于调查户数`);
          }
        });

        return { hasError, errorMessages };
      },
      updateEvaluationFields() {
        const houseSize = this.dataForm.houseSize;

      // 确保户数为正数
      if (houseSize <= 0) {
        this.evaluationResults = {}; // 重置结果
        return;
      }
      // 初始化评估项
        this.evaluationItems = [
            { label: '土壤质地C11', key: 'c11', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '耕前植被情况C12', key: 'c12', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '种植方式C13', key: 'c13', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '土壤特性C14', key: 'c14', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '耕后地表平整情况C21', key: 'c21', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '碎土情况C22', key: 'c22', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '耕深满足农艺要求情况C23', key: 'c23', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '植被覆盖情况C24', key: 'c24', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '驱动轮滑转情况C31', key: 'c31', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '大小田块适用情况C32', key: 'c32', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '地头转弯情况C33', key: 'c33', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '机耕道及田间行走C34', key: 'c34', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 },
            { label: '可靠性用户满意度', key: 'userState', excellentCount: 0, goodCount: 0, averageCount: 0, belowAverageCount: 0, poorCount: 0 }
        ];
      },
      //获取项目列表
      getprojectList() {
        this.$http({
          url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
          method: 'post',
          data: this.$http.adornData({
          })
        }).then((data) => {
          if (data && data.code === 0) {
            console.log(data.productList)
            this.projectList = data.productList
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      recalculateAll() {
        this.evaluationItems.forEach(item => {
          const excellentCount = parseInt(item.excellentCount) || 0;
          const goodCount = parseInt(item.goodCount) || 0;
          const averageCount = parseInt(item.averageCount) || 0;
          const belowAverageCount = parseInt(item.belowAverageCount) || 0;
          const poorCount = parseInt(item.poorCount) || 0;

          const totalScore = (excellentCount * 5) + (goodCount * 4) + (averageCount * 3) + (belowAverageCount * 2) + (poorCount * 1);
          if (item.key === 'userState') {
              this.dataForm.userState = totalScore * 0.1 * 20; 
              this.dataForm.userState = this.dataForm.userState.toFixed(2);
              return; 
          }

          const calculatedValue = (totalScore / Math.max(1, this.dataForm.houseSize)) * 0.25; // 除以总户数

          // 更新相应的c值
          this.dataForm[item.key] = calculatedValue.toFixed(2);
          this.calculateAverage();
        });
      },
       calculateAverage() {
        const group1 = [
            parseFloat(this.dataForm.c11) || 0,
            parseFloat(this.dataForm.c12) || 0,
            parseFloat(this.dataForm.c13) || 0,
            parseFloat(this.dataForm.c14) || 0
        ];

        const group2 = [
            parseFloat(this.dataForm.c21) || 0,
            parseFloat(this.dataForm.c22) || 0,
            parseFloat(this.dataForm.c23) || 0,
            parseFloat(this.dataForm.c24) || 0
        ];

        const group3 = [
            parseFloat(this.dataForm.c31) || 0,
            parseFloat(this.dataForm.c32) || 0,
            parseFloat(this.dataForm.c33) || 0,
            parseFloat(this.dataForm.c34) || 0
        ];

        const avg1 = group1.reduce((sum, value) => sum + value, 0) * 0.3;
        const avg2 = group2.reduce((sum, value) => sum + value, 0) * 0.5;
        const avg3 = group3.reduce((sum, value) => sum + value, 0) * 0.2;
        const totalAverage = avg1 + avg2 + avg3;

        // 将计算结果存储到备注字段
        this.dataForm.remark = totalAverage;
    },
      init (id) {
        this.isEditMode =false;
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/usersurveysummary/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then((data) => {
              if (data && data.code === 0) {
                this.isEditMode = true;
                this.dataForm.projectNum = data.userSurveySummary.projectNum
                this.dataForm.houseSize = data.userSurveySummary.houseSize
                this.dataForm.faultState = data.userSurveySummary.faultState
                this.dataForm.userState = data.userSurveySummary.userState
                // 如果后端返回的 evaluationItems 是 JSON 字符串，解析它
                if (data.userSurveySummary.evaluationItems) {
                  this.evaluationItems = JSON.parse(data.userSurveySummary.evaluationItems);
                } else {
                  this.evaluationItems = []; // 如果没有数据，初始化为空数组
                }
                this.dataForm.c11 = data.userSurveySummary.c11
                this.dataForm.c12 = data.userSurveySummary.c12
                this.dataForm.c13 = data.userSurveySummary.c13
                this.dataForm.c14 = data.userSurveySummary.c14
                this.dataForm.c21 = data.userSurveySummary.c21
                this.dataForm.c22 = data.userSurveySummary.c22
                this.dataForm.c23 = data.userSurveySummary.c23
                this.dataForm.c24 = data.userSurveySummary.c24
                this.dataForm.c31 = data.userSurveySummary.c31
                this.dataForm.c32 = data.userSurveySummary.c32
                this.dataForm.c33 = data.userSurveySummary.c33
                this.dataForm.c34 = data.userSurveySummary.c34
                this.dataForm.remark = data.userSurveySummary.remark
                this.dataForm.summaryName = data.userSurveySummary.summaryName
                this.dataForm.summaryId = data.userSurveySummary.summaryId
                this.dataForm.checkerName = data.userSurveySummary.checkerName
                this.dataForm.checkerId = data.userSurveySummary.checkerId
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 调用验证方法
            const { hasError, errorMessages } = this.validateEvaluationItems();

            if (hasError) {
              this.$message.warning(errorMessages.join('\n'));
              return; // 提交中止
            }
            const remark = this.dataForm.remark !== null && this.dataForm.remarkValue !== ''
                ? this.dataForm.remarkValue // 使用校验值
                : this.dataForm.remark; // 否则使用计算值
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/usersurveysummary/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'projectNum': this.dataForm.projectNum,
                'houseSize': this.dataForm.houseSize,
                'faultState': this.dataForm.faultState,
                'userState': this.dataForm.userState,
                'c11': this.dataForm.c11,
                'c12': this.dataForm.c12,
                'c13': this.dataForm.c13,
                'c14': this.dataForm.c14,
                'c21': this.dataForm.c21,
                'c22': this.dataForm.c22,
                'c23': this.dataForm.c23,
                'c24': this.dataForm.c24,
                'c31': this.dataForm.c31,
                'c32': this.dataForm.c32,
                'c33': this.dataForm.c33,
                'c34': this.dataForm.c34,
                'remark': remark,
                'summaryName': this.dataForm.summaryName,
                'summaryId': this.dataForm.summaryId,
                'checkerName': this.dataForm.checkerName,
                'checkerId': this.dataForm.checkerId,
                'evaluationItems': JSON.stringify(this.evaluationItems)
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
